package cn.edu.stu.syllabus.repository.library.local;

import java.util.List;

import cn.edu.stu.syllabus.dao.BookEntryDao;
import cn.edu.stu.syllabus.repository.library.BookStarDataSource;
import cn.edu.stu.syllabus.utils.ListUtils;
import rx.Observable;

/**
 * Created by daidaijie on 2017/4/1.
 */

public class BookStarLocalDataSource implements BookStarDataSource {

    BookEntryDao mBookEntryDao;

    public BookStarLocalDataSource(BookEntryDao BookEntryDao) {
        this.mBookEntryDao = BookEntryDao;
    }

    @Override
    public void starBookEntry(BookEntry BookEntry) {
        mBookEntryDao.insertOrReplace(BookEntry);
    }

    @Override
    public void unstarBookEntry(BookEntry BookEntry) {
        BookEntry BookEntryInDb = getBookEntryInDb(BookEntry);
        mBookEntryDao.delete(BookEntryInDb);
    }

    @Override
    public boolean isExistEntry(BookEntry BookEntry) {
        return getBookEntryInDb(BookEntry) != null;
    }

    @Override
    public Observable<List<BookEntry>> getStarBookEntries(long lastPosition, int pageNum) {
        return Observable.just(getBookEntriesIndb(lastPosition, pageNum));
    }

    private List<BookEntry> getBookEntriesIndb(long lastPosition, int pageNum) {
        List<BookEntry> BookEntries = mBookEntryDao
                .queryBuilder()
                .where(BookEntryDao.Properties.LocalId.lt(lastPosition))
                .limit(pageNum)
                .orderDesc(BookEntryDao.Properties.LocalId)
                .build().list();

        return BookEntries;
    }

    private BookEntry getBookEntryInDb(BookEntry BookEntry) {
        List<BookEntry> BookEntries = mBookEntryDao
                .queryBuilder().where(BookEntryDao.Properties.RemoteId.eq(BookEntry.getRemoteId()))
                .build().list();
        if (ListUtils.getListSizeSafety(BookEntries) == 0) {
            return null;
        } else {
            return BookEntries.get(0);
        }
    }
}
